import { useState, useEffect, useLayoutEffect, useRef, useMemo } from "react";

import EmojiPicker, { Theme as EmojiTheme } from "emoji-picker-react";
import { Dialog, Form, Input, Toast } from "antd-mobile";
import styles from "./settings.module.scss";
import ResetIcon from "../icons/reset.svg";
import CloseIcon from "../icons/close.svg";
import ClearIcon from "../icons/clear.svg";
import EditIcon from "../icons/edit.svg";
import { useAuthStore } from "@/store//auth";
import { inNestedIframe, isMobile,isWebView } from "../utils/utils";
import { List, ListItem, Popover } from "./ui-lib";

import { IconButton } from "./button";
import { SubmitKey, useChatStore, Theme } from "@/store";
import { Avatar, PromptHints } from "./home";

import Locale, { AllLangs, changeLang, getLang } from "../locales";
import { SearchService, usePromptStore } from "@/store/prompt";
import { EyeInvisibleOutline, EyeOutline } from "antd-mobile-icons";

interface IChangePasswordForm {
  newPwd: string;
  newPwdRepeat: string;
}
function SettingItem(props: {
  title: string;
  subTitle?: string;
  children: JSX.Element;
}) {
  return (
    <ListItem>
      <div className={styles["settings-title"]}>
        <div>{props.title}</div>
        {props.subTitle && (
          <div className={styles["settings-sub-title"]}>{props.subTitle}</div>
        )}
      </div>
      {props.children}
    </ListItem>
  );
}

export function Settings(props: { closeSettings: () => void }) {
  const [showEmojiPicker, setShowEmojiPicker] = useState(false);
  const [config, updateConfig, updateAvatar, resetConfig, clearAllData] =
    useChatStore((state) => [
      state.config,
      state.updateConfig,
      state.updateAvatar,
      state.resetConfig,
      state.clearAllData,
    ]);

  useEffect(() => {}, []);

  const promptStore = usePromptStore();
  const builtinCount = SearchService.count.builtin;
  const customCount = promptStore.prompts.size ?? 0;
  const [modalVisible, setModalVisible] = useState(false);

  const handleOpenModal = (): void => {
    setModalVisible(true);
  };

  const handleCloseModal = (): void => {
    setModalVisible(false);
  };
  // const [enableDarkMode, setEnableDarkMode] = useState(true);

  return (
    <>
      <div className={styles["window-header"]}>
        <div className={styles["window-header-title"]}>
          <div className={styles["window-header-main-title"]}>
            {Locale.Settings.Title}
          </div>
          <div className={styles["window-header-sub-title"]}>
            {Locale.Settings.SubTitle}
          </div>
        </div>
        <div className={styles["window-actions"]}>
          <div className={styles["window-action-button"]}>
            <IconButton
              icon={<ClearIcon />}
              onClick={clearAllData}
              bordered
              title={Locale.Settings.Actions.ClearAll}
            />
          </div>
          <div className={styles["window-action-button"]}>
            <IconButton
              icon={<ResetIcon />}
              onClick={resetConfig}
              bordered
              title={Locale.Settings.Actions.ResetAll}
            />
          </div>
          <div className={styles["window-action-button"]}>
            <IconButton
              icon={<CloseIcon />}
              onClick={props.closeSettings}
              bordered
              title={Locale.Settings.Actions.Close}
            />
          </div>
        </div>
      </div>
      <div className={styles["settings"]}>
        <List>
          {inNestedIframe() ? (
            <></>
          ) : (
            <SettingItem title={Locale.Settings.Avatar}>
              <Popover
                onClose={() => setShowEmojiPicker(false)}
                content={
                  <EmojiPicker
                    width={300}
                    lazyLoadEmojis
                    theme={EmojiTheme.AUTO}
                    onEmojiClick={(e) => {
                      updateAvatar(e.unified);
                      setShowEmojiPicker(false);
                    }}
                  />
                }
                open={showEmojiPicker}
              >
                <div
                  className={styles.avatar}
                  onClick={() => setShowEmojiPicker(true)}
                >
                  <Avatar role="user" />
                </div>
              </Popover>
            </SettingItem>
          )}

          <SettingItem title={Locale.Settings.SendKey}>
            <select
              value={config.submitKey}
              onChange={(e) => {
                updateConfig(
                  (config) =>
                    (config.submitKey = e.target.value as any as SubmitKey),
                );
              }}
            >
              {Object.values(SubmitKey).map((v) => (
                <option value={v} key={v}>
                  {v}
                </option>
              ))}
            </select>
          </SettingItem>

          <ListItem>
            <div className={styles["settings-title"]}>
              {Locale.Settings.Theme}
            </div>
            <select
              value={config.theme}
              onChange={(e) => {
                updateConfig(
                  (config) => (config.theme = e.target.value as any as Theme),
                );
              }}
            >
              {Object.values(Theme).map((v) => (
                <option value={v} key={v}>
                  {v}
                </option>
              ))}
            </select>
          </ListItem>

          <SettingItem title={Locale.Settings.Lang.Name}>
            <select
              value={getLang()}
              onChange={(e) => {
                changeLang(e.target.value as any);
              }}
            >
              {AllLangs.map((lang) => (
                <option value={lang} key={lang}>
                  {Locale.Settings.Lang.Options[lang]}
                </option>
              ))}
            </select>
          </SettingItem>

          <SettingItem
            title={Locale.Settings.FontSize.Title}
            subTitle={Locale.Settings.FontSize.SubTitle}
          >
            <input
              className="setting"
              type="range"
              title={`${config.fontSize ?? 14}px`}
              value={config.fontSize}
              min="12"
              max="18"
              step="1"
              onChange={(e) =>
                updateConfig(
                  (config) =>
                    (config.fontSize = Number.parseInt(e.currentTarget.value)),
                )
              }
            ></input>
          </SettingItem>

          {/* <div className="no-mobile">
            <SettingItem title={Locale.Settings.TightBorder}>
              <input className="setting"
                type="checkbox"
                checked={config.tightBorder}
                onChange={(e) =>
                  updateConfig(
                    (config) => (config.tightBorder = e.currentTarget.checked),
                  )
                }
              ></input>
            </SettingItem>
          </div> */}
        </List>
        {/* <List>
          <SettingItem
            title={Locale.Settings.Prompt.Disable.Title}
            subTitle={Locale.Settings.Prompt.Disable.SubTitle}
          >
            <input
              className="setting"
              type="checkbox"
              checked={config.disablePromptHint}
              onChange={(e) =>
                updateConfig(
                  (config) =>
                    (config.disablePromptHint = e.currentTarget.checked),
                )
              }
            ></input>
          </SettingItem>

          <SettingItem
            title={Locale.Settings.Prompt.List}
            subTitle={Locale.Settings.Prompt.ListCount(
              builtinCount,
              customCount,
            )}
          >
            <IconButton
              icon={<EditIcon />}
              text={Locale.Settings.Prompt.Edit}
              onClick={() => showToast(Locale.WIP)}
            />
          </SettingItem>
        </List>
        <List>
          <SettingItem
            title={Locale.Settings.HistoryCount.Title}
            subTitle={Locale.Settings.HistoryCount.SubTitle}
          >
            <input
              className="setting"
              type="range"
              title={config.historyMessageCount.toString()}
              value={config.historyMessageCount}
              min="2"
              max="25"
              step="2"
              onChange={(e) =>
                updateConfig(
                  (config) =>
                    (config.historyMessageCount = e.target.valueAsNumber),
                )
              }
            ></input>
          </SettingItem>

          <SettingItem
            title={Locale.Settings.CompressThreshold.Title}
            subTitle={Locale.Settings.CompressThreshold.SubTitle}
          >
            <input
              className="setting"
              type="number"
              min={500}
              max={4000}
              value={config.compressMessageLengthThreshold}
              onChange={(e) =>
                updateConfig(
                  (config) =>
                    (config.compressMessageLengthThreshold =
                      e.currentTarget.valueAsNumber),
                )
              }
            ></input>
          </SettingItem>
        </List> */}
        {inNestedIframe() ? (
          <></>
        ) : (
          <List>
            <SettingItem
              title={Locale.Settings.ChangePassword.Title}
              subTitle={Locale.Settings.ChangePassword.SubTitle}
            >
              <IconButton
                icon={<EditIcon />}
                text={Locale.Settings.Prompt.Edit}
                onClick={() => {
                  handleOpenModal();
                }}
              />
            </SettingItem>
          </List>
        )}

        <ChangePasswordModal
          visible={modalVisible}
          onClose={handleCloseModal}
        />
      </div>
    </>
  );
}

function ChangePasswordModal({
  visible,
  onClose,
}: {
  visible: boolean;
  onClose: () => void;
}) {
  const [form] = Form.useForm<IChangePasswordForm>();
  const authStore = useAuthStore.getState();
  const onSubmit = () => {
    return form.validateFields().then((values) => {
      if (values.newPwd !== values.newPwdRepeat) {
        Toast.show({
          icon: "fail",
          content: Locale.Settings.ChangePassword.Pattern,
        });
        return;
      }
      return authStore
        .changePwd({
          newPwd: values.newPwd,
        })
        .then(onClose);
    });
  };
  const [newPwdRepeatVisible, setNewPwdRepeatVisible] = useState<boolean>(
    isMobile(),
  );
  const [newPwdVisible, setNewPwdVisible] = useState<boolean>(isMobile());
  return (
    <Dialog
      forceRender
      title={Locale.Settings.ChangePassword.Title}
      visible={visible}
      content={
        <Form form={form} layout="vertical">
          {/* <Form.Item
            label={Locale.Settings.ChangePassword.OldPwd.Label}
            name="oldPwd"
            rules={[
              {
                required: true,
                message: Locale.Settings.ChangePassword.OldPwd.Required,
              },
              {
                pattern: /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[\W_]).{8,}$/,
                message: Locale.Settings.ChangePassword.OldPwd.Pattern,
              },
            ]}
          >
            <div className={styles.password}>
              <Input
                className={styles.input}
                placeholder={Locale.Settings.ChangePassword.OldPwd.Placeholder}
                type={oldPwdVisible ? "text" : "password"}
              />
              <div className={styles.eye}>
                {!oldPwdVisible ? (
                  <EyeInvisibleOutline onClick={() => setOldPwdVisible(true)} />
                ) : (
                  <EyeOutline onClick={() => setOldPwdVisible(false)} />
                )}
              </div>
            </div>
          </Form.Item> */}
          <Form.Item
            label={Locale.Settings.ChangePassword.NewPwd.Label}
            name="newPwd"
            rules={[
              {
                required: true,
                message: Locale.Settings.ChangePassword.NewPwd.Required,
              },
              {
                pattern: /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[\W_]).{8,}$/,
                message: Locale.Settings.ChangePassword.NewPwd.Pattern,
              },
            ]}
          >
            <div className={styles.password}>
              <Input
                className={styles.input}
                placeholder={Locale.Settings.ChangePassword.NewPwd.Placeholder}
                type={newPwdVisible ? "text" : "password"}
              />
              <div className={styles.eye}>
                {!newPwdVisible ? (
                  <EyeInvisibleOutline onClick={() => setNewPwdVisible(true)} />
                ) : (
                  <EyeOutline onClick={() => setNewPwdVisible(false)} />
                )}
              </div>
            </div>
          </Form.Item>
          <Form.Item
            label={Locale.Settings.ChangePassword.NewPwdRepeat.Label}
            name="newPwdRepeat"
            rules={[
              {
                required: true,
                message: Locale.Settings.ChangePassword.NewPwdRepeat.Required,
              },
              {
                pattern: /^(?=.*\d)(?=.*[a-z])(?=.*[A-Z])(?=.*[\W_]).{8,}$/,
                message: Locale.Settings.ChangePassword.NewPwdRepeat.Pattern,
              },
            ]}
          >
            <div className={styles.password}>
              <Input
                className={styles.input}
                placeholder={
                  Locale.Settings.ChangePassword.NewPwdRepeat.Placeholder
                }
                type={newPwdRepeatVisible ? "text" : "password"}
              />
              <div className={styles.eye}>
                {!newPwdRepeatVisible ? (
                  <EyeInvisibleOutline
                    onClick={() => setNewPwdRepeatVisible(true)}
                  />
                ) : (
                  <EyeOutline onClick={() => setNewPwdRepeatVisible(false)} />
                )}
              </div>
            </div>
          </Form.Item>
        </Form>
      }
      onClose={onClose}
      actions={[
        [
          {
            key: "cancel",
            text: Locale.Settings.Actions.Cancel,
            onClick: () => {
              onClose();
            },
          },
          {
            key: "confirm",
            text: Locale.Settings.Actions.Confirm,
            onClick: async () => {
              await onSubmit();
            },
          },
        ],
      ]}
    />
  );
}
